<?php
/*
 * 
 * Enter description here...
 *	
 * STATUS_DISABLE 0 
 * STATUS_ABLE 1 
 */

class Upload extends CActiveRecord {
	public static function model($className = __CLASS__) {
		return parent::model ( $className );
	}
	
	public function tableName() {
		return '{{upload}}';
	}
	
	public function rules() {
		return array (
			
			array (
				
				'filename,filetype', 
				'required', 
				'message' => '不能为空' 
			), 
			array (
				
				'unid,dirid,originalname', 
				'safe' 
			) 
		);
	}
	
	//	public function relations() {
	//		return array ();
	//	}
	

	public function attributeLabels() {
		return array (
			
			'id' => 'id', 
			'filename' => 'filename', 
			'filetype' => 'filetype', 
			'unid' => 'unid', 
			'dirid' => 'dirid',
		    'originalname'=>'Originalname',
		);
	}
	
	function fileUpload($dirName, $filename, $tmp_name,$dirid,$filesize,$filetype,$unid = -1) {
		@mkdir ( $dirName, 0777 );
		$uploadFile = "$dirName/" . md5 ( $filename . time () );
		if (copy ( $tmp_name, $dirName . '/' . md5 ( $filename . time () ).'.'.$filetype )) {
			$this->filename = md5 ( $filename . time () );
			$this->filetype = $filetype;
			$this->unid = $unid;
			$this->originalname =$filename;
			$this->dirid = $dirid;
			$this->filesize = $filesize;
			$this->save ();
		}
	}
	
	
	public function delFile($id,$path){
		
			$this->deleteByPk($id);
			$ret=@unlink($path);
			return $ret;
	}
	
	
   public function delFileByDir($id){
		    $row=$this->findAll(array("condition"=>"dirid=$id"));
		    if($row){
		    $ret=CommonFunc::YiiobjectToArray($row,"all");
		    foreach ($ret as $v) {
		    	$id=$v['id'];
		    	$path="uploads/".$v['filename'].".".$v['filetype'];
		    	$ret=$this->delFile($id, $path);
		    }
		    }else {
		    	
		    	$ret=FALSE;
		    }   	
   	        
			return $ret;
	}
	
	
   function getFileListAll($dirid,$offset=NULL,$limit=NULL){
   	 	   $ret=$this->findAll(array("condition"=>"dirid=$dirid"));    	
   	       return CommonFunc::YiiobjectToArray($ret,"all");
   	       
   }
	
	
	
	function getFiles($unid = -1) {
		$rows = $this->findAll ( array (
			
			"condition" => "unid='$unid'" 
		) );
		return CommonFunc::YiiobjectToArray ( $rows, "all" );
	}
}
?>
